<template>
    <div class="login">
        <!--  v-model控制对话框的显示与否      -->
        <el-dialog v-model="userStore.visible"
                   title="登录" width="700"
                   style=".el-dialog__body{
                        height: 500px;
                        border-top: 1px solid #ccc;
                        border-bottom: 1px solid #ccc;
                   }"
                   ref="dialog"
                   @close="close"

        >
            <!--对话框整体部分-->
            <el-row>
                <!-- 左侧文本框 -->
                <el-col :span="12">
                    <div v-show="way == 0">
                        <el-form class="form" :rules="rules" :model="login" ref="form">
                            <el-form-item prop="phone">
                                <el-input placeholder="请输入手机号码" v-model="login.phone"
                                          clearable :prefix-icon="User" style="margin: 10px"></el-input>
                            </el-form-item>
                            <el-form-item prop="pass">
                                <el-input placeholder="请输入验证码" v-model="login.code"
                                          clearable :prefix-icon="Lock" style="margin: 10px"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button :disabled="!isPhone || time">
                                    <Time v-if="time" :time="time" @getTime="getTime"/>
                                    <span v-else @click="getCode">获取验证码</span>
                                </el-button>
                            </el-form-item>
                                <el-button type="primary" size="default"
                                           @click="Login" style="width: 100%"
                                           :disabled="!isPhone || login.code.length!=6 || login.code!==userStore.code"
                                >
                                    用户登录
                                </el-button>
                            <div class="bottom" @click="changeWay">
                                <p>微信扫码登录</p>
                                <img src="../../assets/微信.png" alt="">
                            </div>
                        </el-form>
                    </div>
                    <div class="wechat" v-show="way == 1">
                        <div id="login_container"></div>
                        <div class="bottom" @click="way = 0">
                            <p>手机账号登录</p>
                            <img src="../../assets/手机.png" alt="">
                        </div>
                    </div>
                </el-col>
                <!-- 右侧二维码 -->
                <el-col :span="12">
                    <div class="leftContent">
                        <div class="top">
                            <div class="item">
                                <div class="tu"><img src="../../assets/login.png" alt=""></div>
                                <img src="../../assets/微信2.png" alt="">
                                <p>微信扫一扫关注</p>
                                <p>“快速预约挂号”</p>
                            </div>
                            <div class="item">
                                <div class="tu"><img src="../../assets/code.png" alt=""></div>
                                <img src="../../assets/手机.png" alt="">
                                <p>扫一扫下载</p>
                                <p>“预约挂号App”</p>
                            </div>
                        </div>
                        <p class="tip">官方指定平台</p>
                        <p class="tip">快速挂号 安全放心</p>
                    </div>
                </el-col>
            </el-row>
            <!-- 底部按钮 -->
            <template #footer>
                <el-button type="primary" @click="close">关闭窗口</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="Login">
    // 获取仓库内容，主要是visible控制显示与隐藏
    import useUserStore from "@/store/modules/user";
    import {ref, reactive, computed, watch} from "vue";
    import {User,Lock} from "@element-plus/icons-vue";
    import Time from "./Time.vue";
    import {ElMessage} from "element-plus";
    import {useRoute,useRouter} from "vue-router";
    // 引入微信扫码登录参数
    import {reqWxLogin} from "@/api/hospital";
    import type {WxLoginResponseData} from "@/api/hospital/type";

    let $router = useRouter();
    let $route = useRoute();
    let userStore = useUserStore();
    // 控制登录方式
    let way = ref<number>(0);
    const changeWay = async () =>{
        way.value = 1;

        // 发送获取二维码的参数
        let redirect_uri = encodeURIComponent(window.location.origin+'/wxlogin');
        let result:WxLoginResponseData = await reqWxLogin(redirect_uri);
        //@ts-ignore
        new WxLogin({
            self_redirect_uri: true, // 在手机点击确认后在iframe内跳转到redirect_url
            id: "login_container",   // 二维码显示容器
            appid: result.data.appid,  // 应用唯一标识
            scope: "snsapi_login",    // 微信扫码登录页面是否授权
            redirect_uri: result.data.redirectUri,  // 填写授权回调域路径，微信服务器向后台推送code的地址
            state: result.data.state,          // 重定向地址
            style: "black",  // 二维码外观
            href: ""
        });
    }
    // 登录信息
    const login = reactive({
        phone: '',
        code: ''
    });
    let form = ref<any>();

    const checkPhone = (rule: any,value: any,callback: any) => {
        if (!isPhone.value) {
            callback(new Error('请输入正确的手机号码'))
        } else {
            callback();
        }
    }
    const checkPass = (rule: any,value: any,callback: any) => {
        if (!login.code) {
            callback(new Error('请输入验证码'))
        } else if (login.code !== userStore.code) {
            callback(new Error('验证码错误'))
        } else {
            callback();
        }
    }


    // 表单校验提示信息
    const rules = reactive({
          phone: [{ validator: checkPhone, trigger: 'change' }],
          pass: [{ validator: checkPass,trigger: 'change' }]
        })

    // 手机表单数据：手机号码是否正确
    let isPhone = computed(()=>{
        const reg = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
        return reg.test(login.phone)
    })

    // 获取验证码按钮调用
    const getCode = async () =>{
        if(!isPhone.value || time.value) return;
        try {
            await userStore.getCode(login.phone);
            login.code = userStore.code
        }catch (error){
            ElMessage({
                message: '获取验证码失败',
                type: 'error'
            })
        }
        // 开启倒计时
        time.value = true
    }

    // 控制倒计时的出现
    const time = ref<boolean>(false)
    // 自定义事件
    const getTime = (arg:boolean) =>{
        time.value = arg
    }

    // 登录按钮
    const Login = async () =>{
        try {
            await userStore.userLogin(login);
            userStore.visible = false;
            // 判断是否有跳转地址（在登录之前是否点击其他页面）
            let redirect = $route.query.redirect as string;
            if (redirect){
                await $router.push(redirect);
            }else{
                await $router.push({path:'/home'});
            }
        }catch (error){
            ElMessage({
                message: '登录失败',
                type: 'error'
            })
        }
    }

    const close = () =>{
        // 清空数据
        Object.assign(login,{phone:'',code:''})
        // 清除校验规则
        form.value.resetFields();
        userStore.visible = false;
    }

    // 监听场景数值登录方式
    watch(()=>way.value,( val:number)=>{
        if(val === 1){
            userStore.queryState();
        }
    },{immediate:true})
</script>

<style scoped>
    .form{
        padding: 20px;
        border: 1px solid #ccc;
    }
    .bottom{
        display: flex;
        flex-direction: column;
        align-items: center;
        p{
            margin: 10px 0;
        }
    }
    .bottom:hover{
        cursor: pointer;
    }
    .leftContent{
        .top{
            display: flex;
            justify-content: space-around;
            .item{
                display: flex;
                flex-direction: column;
                align-items: center;
                .tu{
                    img{
                        width: 130px;
                        height: 130px;
                    }
                }
                img{
                    width: 16px;
                    height: 16px;
                }
                p{
                    margin: 5px 0;
                }
            }
        }
        .tip{
            text-align: center;
            margin: 20px 0;
            font-size: 20px;
            font-weight: 900;
        }
    }
</style>